package zt.song.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @Author 宋伟宁
 * @Date 2023/11/17
 * @Version 1.0
 **/
@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Resource
    private MyAuthericFaileHandler myAuthericFaileHandler;

    @Resource
    private MySuccessHandler mySuccessHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{

         http.authorizeHttpRequests( resp ->
                 //放过登录
                 resp.requestMatchers("/login").permitAll()
                         .requestMatchers("/admin/**").hasAuthority("admin")
                         .requestMatchers("/user/**").hasAuthority("user")
                         .requestMatchers("/app").permitAll()

                  .anyRequest().authenticated()
                 );

         http.formLogin( (form)-> {
             //登录页面
             form.loginPage("/login").permitAll()
              //成功的处理
                     .defaultSuccessUrl("/index")
//                     .successHandler(this.mySuccessHandler)

                     //.successHandler(new MySuccessHandler("http://www.baidu.com"))
                     .failureHandler(myAuthericFaileHandler);

                      //错误的页面处理
                     //form.failureUrl("/logerr");
                 }
                 );

         http.csrf(Customizer.withDefaults());
         return  http.build();

    }

//    @Bean
//    public UserDetailsService userDetailsService(){
//        UserDetails  u1= User
//                .withUsername("user")
//                .password("1234")
//                .roles("user")
//                .build();
//
//        return new InMemoryUserDetailsManager(u1);
//
//    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
